package com.xy.shard.config;

import com.google.common.collect.Range;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import org.apache.shardingsphere.sharding.exception.syntax.UnsupportedShardingOperationException;
import org.springframework.stereotype.Service;

import java.util.*;


public class MyComplexAl implements ComplexKeysShardingAlgorithm<Long> {

    private static final String SHARING_COLUMNS_KEY = "sharding-columns";

    private Properties props;
    //保留配置的分片键。在当前算法中其实是没有用的。
    private Collection<String> shardingColumns;

    @Override
    public void init(Properties props) {
        this.props = props;
        this.shardingColumns = getShardingColumns(props);
    }

    /**
     * 实现自定义分片算法
     *
     * @param availableTargetNames 在actual-nodes中配置了的所有数据分片
     * @param shardingValue        组合分片键
     * @return 目标分片
     */
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, ComplexKeysShardingValue<Long> shardingValue) {
        List<String> result = new ArrayList<>();
        //user_id范围包含了1001后，就按照cid的奇偶分片
        String logicTableName = shardingValue.getLogicTableName();//操作的逻辑表 course
        logicTableName = logicTableName + "_1";
        return Arrays.asList(logicTableName);
    }

    private Collection<String> getShardingColumns(final Properties props) {
        String shardingColumns = props.getProperty(SHARING_COLUMNS_KEY, "");
        return shardingColumns.isEmpty() ? Collections.emptyList() : Arrays.asList(shardingColumns.split(","));
    }

    public void setProps(Properties props) {
        this.props = props;
    }

    @Override
    public Properties getProps() {
        return this.props;
    }

    @Override
    public String getType() {
        return "MYCOMPLEX";
    }
}
